#!/usr/bin/python

import re
import os
import datetime
import fnmatch

from django.contrib.auth.models import User
from movie.vote.models import Movie
import imdb

PROMPT = False

def FindIMDBFromNfo(path):
  if not os.path.exists(path):
    return None

  regex = re.compile(r'(http://.*?imdb\.com.*?)(\s|$)')
  for nfo in fnmatch.filter(os.listdir(path), '*.[Nn][Ff][Oo]'):
    for line in file(os.path.join(path, nfo)).readlines():
      found = regex.findall(line)
      if found:
        url = found[0][0]
        if not url.endswith('/'):
          url += '/'
        return url
  return None

def AddMovie(name, imdb_url, added_by_user='valankar'):
  print 'add movie: %s %s' % (name, imdb_url)
  if PROMPT:
    answer = raw_input('Continue? [y] ')
    if answer and not answer.lower().startswith('y'):
      return
  user = User.objects.get(username=added_by_user)
  m = Movie(name=name, date_added=datetime.datetime.now(), imdb_url=imdb_url)
  m.save()

def ImportDir(path):
  imdb_access = imdb.IMDb()
  for movie_name in os.listdir(path):
    if not os.path.isdir(os.path.join(path, movie_name)):
      continue
    if movie_name.startswith('.'):
      continue
    if os.path.exists(os.path.join(path, movie_name, '.noimport')):
      continue
    if movie_name.count('.') > 1:
      continue
    title = movie_name.title()
    # Check if movie name already exists in db
    if Movie.objects.filter(name__iexact=title):
      continue
    # Try to find IMDB URL in nfo files
    url = FindIMDBFromNfo(os.path.join(path, movie_name))
    if not url:
      # No useful nfo, go to IMDB
      try:
        m = imdb_access.search_movie(movie_name)[0]
        url = imdb_access.get_imdbURL(m)
      except IndexError:
        print 'Could not find on IMDB: %s' % (movie_name,)
        continue
      if not url:
        print 'Wierdness from imdb_access: %s' % (movie_name,)
        continue
    
    # Check if imdb ID already exists in db
    # http://akas.imdb.com/title/tt0389328/
    imdb_id = filter(lambda x: x, url.split('/'))[-1] + '/'
    found = Movie.objects.filter(imdb_url__endswith=imdb_id)
    if found:
      print title
      print 'Another movie exists already with this IMDB url: %s' % (found[0].name)
      continue
    AddMovie(title, url)


if __name__ == '__main__':
  ImportDir('/mnt/movies')
